package Concurrency2.Chapter03_CAS_Atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Instruction: 原子类AtomicInteger的使用
 * Author：@author MaLi
 */
public class T03_AtomicInteger {
    public static void main(String[] args) throws InterruptedException {
        int threadAmount = 10;
        CountDownLatch latch = new CountDownLatch(threadAmount);
        ExecutorService service = Executors.newFixedThreadPool(threadAmount);
        AtomicInteger safeIntNum = new AtomicInteger(0);
        int turns = 1000;
        for (int i = 0; i < threadAmount; i++) {
            service.submit(()->{
                int value =safeIntNum.get();
                for (int j = 0; j < turns; j++) {
                    //safeIntNum.incrementAndGet();   //自增1: ++i
                    //safeIntNum.decrementAndGet();   //自减1: --i
                    //safeIntNum.getAndIncrement();   //i++
                    //safeIntNum.getAndDecrement();   //i--
                    //safeIntNum.addAndGet(2);        //自增2:  i+=2 先自增, 在获取
                    //safeIntNum.getAndAdd(2);        //自增2: i+=2 先获取, 再自增
                    //CAS操作: 需要一个记录值
                    //实现自加1
                    while (!safeIntNum.compareAndSet(value, value + 1)) {
                        value = safeIntNum.get();//更新value值
                    }
                }
                latch.countDown();
            });
        }
        latch.await();
        System.out.println("累加结果: "+safeIntNum.get());
        service.shutdown();
    }
}
